﻿using FastExecutor.Base.Util;
using FastExecutor.Base.Design;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FastORM.Applicaiton;
using FastExecutor.Message.Application;

namespace FastExecutor
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //IOC初始化
            InjectUtil.Init();
            //ORM框架初始化
            DBUtil.Init();
            //消息通道初始化
            MessageCenter.GetInstance().Init();
            //对于因为系统更新或其他停机原因导致的未消费的消息重新发送进入订阅通道
            MessageCenter.GetInstance().ReSendAllWaitHandleMessage();
            //系统任务初始化
            InjectUtil.Container.Resolve<TaskUtil>().Init();

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //对Controller默认工程进行自定义替换，实现Controller自动注入
            ControllerBuilder.Current.SetControllerFactory(new FastControllerFactory());

            //依赖框架部署的子项目的监听
            PluginUtil.StartWatch();

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
            {
                Server.ClearError();
                Response.Redirect(CommonUtil.GetRootPath() + "Frame/Error/Error404");
            }
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //默认站点，配置域名,配置虚拟目录的网站直接访问，跳转默认站点
            string FilePath = Context.Request.FilePath;
            if (FilePath.Length - FilePath.Replace("/", String.Empty).Length == 1 || (FilePath.StartsWith("/")) && (FilePath.EndsWith("/") && FilePath.Length - FilePath.Replace("/", String.Empty).Length == 2))
            {
                string DefaultUrl = System.Configuration.ConfigurationManager.AppSettings["DefaultHomeUrl"];
                Context.Response.Redirect(CommonUtil.GetRootPath() + DefaultUrl);
            }
        }
    }
}
